package com.topisv.tms.web.focus;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springside.modules.web.Servlets;

import com.topisv.tms.entity.AreaGroup;
import com.topisv.tms.entity.Customers;
import com.topisv.tms.entity.EdiOrder;
import com.topisv.tms.entity.LogisticsCompany;
import com.topisv.tms.entity.OrdenoSource;
import com.topisv.tms.entity.ShopSource;
import com.topisv.tms.service.AreaGroupService;
import com.topisv.tms.service.CustomersService;
import com.topisv.tms.service.EdiOrderService;
import com.topisv.tms.service.LogisticsCompanyService;
import com.topisv.tms.service.ShopSourceService;
import com.topisv.tms.service.account.ShiroDbRealm.ShiroUser;

/**
 * 集发
 * @author Administrator
 *
 */
@Controller
@RequestMapping({ "/gather" })
public class GatherController {
	private static final Logger logger = LoggerFactory.getLogger(GatherController.class);
	@Autowired
	private EdiOrderService ediOrderService;
	@Autowired
	private CustomersService customersService;
	@Autowired
	private AreaGroupService areaGroupService;
	@Autowired
	private ShopSourceService ShopSourceService;
	@Autowired
	private LogisticsCompanyService logisticsCompanyService;
	
	/**
	 * 导向待处理订单页面
	 * @param model
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "toUnhandleOrderPage")
	public String toUnhandleOrderPage(Model model, ServletRequest request) {
		try {
			ShiroUser curUser = (ShiroUser) SecurityUtils.getSubject().getPrincipal();
		    List<Customers> customers=this.customersService.loadCustomerByAuthority(curUser);
		    model.addAttribute("customers", customers); 
		    String customerCode=customers.get(0).getCustomerCode();
		    //快递公司
			List<LogisticsCompany> cmpList=this.logisticsCompanyService.findAll();
			model.addAttribute("cmpList",cmpList);
			if (StringUtils.isEmpty(customerCode)) {
				return "work/gather/unhandleOrder";
			}
			
			
			//集发目的地网点
			List<AreaGroup> areaGroups=this.areaGroupService.loadAreaGroupByAuthority(customerCode);//.loadByWarehouseType("paiu");
			model.addAttribute("areaGroups", areaGroups);
			
			List<AreaGroup> wmList=this.areaGroupService.loadAreaGroupByAuthority(curUser, customerCode);
			model.addAttribute("wmList", wmList);
			
			//平台
			List<OrdenoSource> ordenoSources=this.customersService.findOrdenoSource(customerCode);
			model.addAttribute("ordenoSources", ordenoSources);
			
			//商家店铺
			List<ShopSource> shopList=this.ShopSourceService.findByCustomerCode(customerCode);
			model.addAttribute("shopList", shopList);
			
			//封装查询参数
			Map<String, Object> searchParams=new HashMap<String, Object>();
			searchParams.put("customerCode", customerCode);
			searchParams.put("orderStatus", "ok");
			searchParams.put("status", "pending");
			searchParams.put("areaGroupCode", areaGroups.get(0).getGroupCode());
			searchParams.put("warehouseCode", wmList.get(0).getGroupCode());
			//查询未处理订单，并区分单件、多件 (默认使用时间优先策略：timefirst)
			Map<String, List<EdiOrder>> orderMap = this.ediOrderService.loadUnhandledOrder(searchParams,"timefirst");
			List<EdiOrder> singleList = orderMap.get("single");
			List<EdiOrder> multiList = orderMap.get("multi");
			model.addAttribute("singleList", singleList);
			model.addAttribute("multiList", multiList);
			model.addAttribute("tab1","active");
			model.addAttribute("customerCode",customerCode);
			model.addAttribute("searchParams", Servlets.encodeParameterStringWithPrefix(searchParams, "_"));

		} catch (Exception e) {
			
			logger.error("error",e);
		}
		return "work/gather/unhandleOrder";
	}
	
	/**
	 * 查询待处理订单数据
	 * @param model
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "query")
	public String query(Model model, ServletRequest request, ServletResponse response) throws Exception {
		logger.info("开始筛选集发订单");
		Map<String, Object> searchParams = Servlets.getParametersStartingWith(request, "_");
		for(String key:searchParams.keySet()){
			logger.info(key+"=="+searchParams.get(key));
		}
		String tacticsType=(String) searchParams.get("tacticsType");
		String fromDateStr=(String) searchParams.get("fromDate");
		String toDateStr=(String) searchParams.get("toDate");
		String customerCode=(String) searchParams.get("customerCode");
		String warehouseCode=(String)searchParams.get("warehouseCode");
		String areaGroupCode=(String)searchParams.get("areaGroupCode");
		String companyCode=(String)searchParams.get("companyCode");
		ShiroUser curUser = (ShiroUser) SecurityUtils.getSubject().getPrincipal();
	    List<Customers> customers=this.customersService.loadCustomerByAuthority(curUser);
	    model.addAttribute("customers", customers); 
	    //快递公司
		List<LogisticsCompany> cmpList=this.logisticsCompanyService.findAll();
		model.addAttribute("cmpList",cmpList);
	    if(customerCode==null){
	    	customerCode=customers.get(0).getCustomerCode();
	    }
		if (StringUtils.isEmpty(customerCode)) {
			return "work/createTask/unhandleOrder";
		}
		
		List<AreaGroup> wmList=this.areaGroupService.loadAreaGroupByAuthority(curUser, customerCode);
		model.addAttribute("wmList", wmList);
		
		//集发目的地网点
		List<AreaGroup> areaGroups=this.areaGroupService.loadAreaGroupByAuthority(customerCode);//loadByWarehouseType("paiu");
		model.addAttribute("areaGroups", areaGroups);
		
		//平台
		List<OrdenoSource> ordenoSources=this.customersService.findOrdenoSource(customerCode);
		model.addAttribute("ordenoSources", ordenoSources);
		//商家店铺
		List<ShopSource> shopList=this.ShopSourceService.findByCustomerCode(customerCode);
		model.addAttribute("shopList", shopList);
		
		
		
		Date fromDate=null;
		Date toDate=null;
		SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		
		if(StringUtils.isNotEmpty(fromDateStr)){
			fromDate=sdf.parse(fromDateStr+" 00:00:00");
		}
		if(StringUtils.isNotEmpty(toDateStr)){
			toDate=sdf.parse(toDateStr+" 23:59:59");
		}
		
		//封装查询参数
		searchParams.put("customerCode", customerCode);
		searchParams.put("fromDate", fromDate);
		searchParams.put("toDate", toDate);
		searchParams.put("orderStatus", "ok");
		searchParams.put("status", "pending");
		searchParams.put("areaGroupCode", areaGroupCode);
		searchParams.put("warehouseCode", warehouseCode);
		searchParams.put("companyCode", companyCode);
		// 查询未处理订单，并区分单件、多件 (默认使用时间优先策略：timefirst)
		Map<String, List<EdiOrder>> orderMap = this.ediOrderService.loadUnhandledOrder(searchParams,tacticsType);
		List<EdiOrder> singleList = orderMap.get("single");
		List<EdiOrder> multiList = orderMap.get("multi");
		model.addAttribute("singleList", singleList);
		model.addAttribute("multiList", multiList);
		model.addAttribute("tab1","active");
		model.addAttribute("customerCode",customerCode);
		model.addAttribute("searchParams", Servlets.encodeParameterStringWithPrefix(searchParams, "_"));

		return "work/gather/unhandleOrder";
	}
}
